import { Cart, CartProduct } from '@/types/store'
import { getModule, Module, Mutation, VuexModule } from 'vuex-module-decorators'
import store from '@/store'
import { Product } from '@/types/model'

interface CartOptionPayload {
  shopId: string
  shopName?: string
  product: Product
}

interface ChangeItemPayload extends CartOptionPayload {
  number: number
}

@Module({ dynamic: true, store, name: 'app', namespaced: true })
export default class AppModule extends VuexModule {
  cartList: Cart = _getLocalStorage()

  @Mutation
  changeCartItem (payload: ChangeItemPayload) {
    const { shopId, product, number, shopName } = payload
    let shopInfo = this.cartList[shopId]
    if (!shopInfo) {
      shopInfo = {
        shopName: shopName as string,
        productList: {}
      }
      this.cartList[shopId] = shopInfo
    }
    let productInfo = shopInfo.productList[product.id]
    if (!productInfo) {
      productInfo = {
        ...product,
        count: 0,
        check: true
      }
      shopInfo.productList[product.id] = productInfo
    }
    productInfo.count += number
    if (number > 0) {
      productInfo.check = true
    }
    if (productInfo.count < 0) {
      productInfo.count = 0
    }
    _setLocalStorage()
  }

  @Mutation
  changItemCheck (payload: CartOptionPayload) {
    const { shopId, product } = payload
    const productInfo = this.cartList[shopId]?.productList?.[product.id] as CartProduct
    productInfo.check = !productInfo.check
    _setLocalStorage()
  }

  @Mutation
  setShopCartSet (shopId: string) {
    const productList = this.cartList[shopId]?.productList
    if (!productList) return
    for (const key in productList) {
      const productInfo = productList[key] as CartProduct
      productInfo.check = true
    }
    _setLocalStorage()
  }

  @Mutation
  clearShopCart (shopId: string) {
    const cartShop = this.cartList[shopId]
    if (!cartShop) return
    cartShop.productList = {}
    _setLocalStorage()
  }
}

export const appStore = getModule(AppModule)

function _setLocalStorage () {
  const str = JSON.stringify(appStore.cartList)
  localStorage.setItem('cartList', str)
}

function _getLocalStorage (): Cart {
  return JSON.parse(localStorage.getItem('cartList') || '{}')
}
